import axios from "axios";
import { useUserStore } from "../store/user";
import { ElMessage } from "element-plus";

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 10000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

request.interceptors.request.use(
  (config) => {
    const { token } = useUserStore();
    // 请求头 这里到时候需要设置token
    if (token) config.headers.Authorization = token;
    return config;
  },
  (err) => {
    console.log(err);
  }
);
request.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (err) => {
    //如果返回401 表示登入过期 提示重新登入
    if(err.response.data.code==401){
      ElMessage.error('登录过期，请重新登录')
    }else{
      ElMessage.error("系统出错！")
    }
    return err;
  }
);

export default request;
